<template>
	<view class="edit-pics">
		<view class="flex flex-wrap">
			<view v-for="(item, index) in allImages" :key="index" class="uploadGroup">
				<u--image 
					:src="item.url" 
					class="image"
					width="210rpx" 
					height="210rpx" ></u--image>
				<view @click="deletePic(index)" class="iconbox">
					<u-icon class="icon" name="close" color="#fff" size="20"></u-icon>
				</view>
			</view>
			<u-upload
				@afterRead="afterRead"
				multiple
				width="210rpx"
				height="210rpx"
			></u-upload>
		</view>
		
		<u-toast ref="uToast"></u-toast>
		
		<view class="actionsFix">
			<u-button 
				class="btn" 
				plain 
				type="primary" 
				:loading="saveLoading"
				@click="submit">保存</u-button>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database()
	const uniCloudStorageExtCo = uniCloud.importObject('ext-storage-co')
	export default {
		data() {
			return {
				allImages: [],
				saveLoading: false
			}
		},
		methods: {
			// 新增图片
			afterRead(event) {
				uni.showLoading({
					title: '图片上传中...'
				})
				let lists = [].concat(event.file)
				this.uploadImages(lists, 0)
			},
			async uploadImages(urls, index) {
				if (index >= urls.length) {
					// 所有图片上传完毕
					uni.hideLoading()
				    return
				}
				const item = urls[index]
				const uploadFileOptionsRes = await uniCloudStorageExtCo.getUploadFileOptions({
					cloudPath: `hxs/${Date.now()}.jpg`, // 支持自定义目录
				})
				const uploadTask = uni.uploadFile({
					...uploadFileOptionsRes.uploadFileOptions,
					filePath: item.url,
					success: () => {
						const res = {
							cloudPath: uploadFileOptionsRes.cloudPath, // 文件云端路径
							fileID: uploadFileOptionsRes.fileID, // 文件ID
							fileURL: uploadFileOptionsRes.fileURL, // 文件URL（如果是私有权限，则此URL是无法直接访问的）
						}
						// 数据库里可直接保存 fileURL 或 fileID
						console.log("上传成功", uploadFileOptionsRes)
						this.allImages.push({
							url: uploadFileOptionsRes.fileURL
						})
						this.uploadImages(urls, index + 1)
					},
					fail: (err) => {
						console.log("上传失败", err)
						uni.hideLoading()
					}
				})
				uploadTask.onProgressUpdate((res) => {
					console.log("监听上传进度", res);
				})
			},
			deletePic(index) {
				this.allImages.splice(index, 1)
			},
			submit() {
				if (!this.allImages.length) {
					uni.$u.toast('您还没有选择图片')
					return
				}
				this.saveLoading = true
				db.collection('hxs-pics').add([
					...this.allImages
				]).then(res => {
					uni.$u.toast('保存成功')
					setTimeout(() => {
						uni.navigateBack()
						uni.$emit('refreshPics')
					}, 1500)
				}).finally(() => {
					this.saveLoading = false
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
.edit-pics {
	padding: 30rpx 30rpx 130rpx;
}
</style>
